<template>
  <div class="movie-filter-base">
    <!-- 排序选项 -->
    <div v-if="showSort" class="mb-6">
      <div class="glass rounded-xl p-5 border border-background-600/50 shadow-xl">
        <div class="flex items-center gap-2 mb-4">
          <div class="w-8 h-8 bg-gradient-to-r from-primary-500/20 to-ai-generated/20 rounded-lg flex items-center justify-center">
            <svg class="w-4 h-4 text-primary-400" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M3 3a1 1 0 000 2v8a2 2 0 002 2h2.586l-1.293 1.293a1 1 0 101.414 1.414L10 15.414l2.293 2.293a1 1 0 001.414-1.414L12.414 14H15a2 2 0 002-2V5a1 1 0 100-2H3zm11.707 4.707a1 1 0 00-1.414-1.414L10 9.586 8.707 8.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
            </svg>
          </div>
          <span class="text-text-primary text-sm font-semibold">排序方式</span>
        </div>
        <div class="flex flex-wrap gap-2.5">
          <button
            v-for="sortOption in sortOptions"
            :key="sortOption.key"
            @click="selectSort(sortOption.key)"
            :class="[
              'group relative flex items-center gap-2 px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200 border backdrop-blur-sm',
              currentSort === sortOption.key
                ? 'bg-gradient-to-r from-primary-600/20 to-ai-generated/20 border-primary-500/30 text-primary-300 shadow-lg shadow-primary-500/10 hover:from-primary-600/30 hover:to-ai-generated/30'
                : 'bg-background-700/30 border-background-600 text-text-secondary hover:bg-background-600/40 hover:border-background-500 hover:text-text-primary hover:shadow-md'
            ]"
          >
            <span class="flex items-center gap-1.5">
              <span class="text-base">{{ sortOption.icon }}</span>
              <span>{{ sortOption.label }}</span>
            </span>
          </button>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div v-if="showFilters" class="card mb-6">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6">
        <!-- 艺术类型筛选 -->
        <div v-if="showGenreFilter">
          <h3 class="text-text-primary font-semibold mb-3">艺术类型</h3>
          <UiSelect
            :model-value="filters.genre"
            :options="genreOptions"
            @update:model-value="(value: string) => selectFilter('genre', value)"
            class="w-full"
            placeholder="选择艺术类型"
          />
        </div>

        <!-- 平行宇宙设定筛选 -->
        <div v-if="showUniverseFilter">
          <h3 class="text-text-primary font-semibold mb-3">平行宇宙设定</h3>
          <UiSelect
            :model-value="filters.universe"
            :options="universeOptions"
            @update:model-value="(value: string) => selectFilter('universe', value)"
            class="w-full"
            placeholder="选择平行宇宙设定"
          />
        </div>

        <!-- 语言筛选 -->
        <div v-if="showLanguageFilter">
          <h3 class="text-text-primary font-semibold mb-3">语言</h3>
          <UiSelect
            :model-value="filters.language"
            :options="languageOptions"
            @update:model-value="(value: string) => selectFilter('language', value)"
            class="w-full"
            placeholder="选择语言"
          />
        </div>

        <!-- 国家/地区筛选 -->
        <div v-if="showCountryFilter">
          <h3 class="text-text-primary font-semibold mb-3">国家/地区</h3>
          <UiSelect
            :model-value="filters.country"
            :options="countryOptions"
            @update:model-value="(value: string) => selectFilter('country', value)"
            class="w-full"
            placeholder="选择国家/地区"
          />
        </div>

        <!-- AI生成筛选 -->
        <div v-if="showAiFilter">
          <h3 class="text-text-primary font-semibold mb-3">AI生成</h3>
          <UiSelect
            :model-value="filters.ai"
            :options="aiOptions"
            @update:model-value="(value: string) => selectFilter('ai', value)"
            class="w-full"
            placeholder="选择AI状态"
          />
        </div>
      </div>

      <!-- 清除筛选按钮 -->
      <div v-if="hasActiveFilters" class="mt-6 flex justify-center">
        <UiButton
          @click="clearFilters"
          variant="ghost"
          size="sm"
          class="text-text-muted hover:text-text-primary"
        >
          <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
          清除所有筛选
        </UiButton>
      </div>
    </div>

    <!-- 统计信息 -->
    <div v-if="showStats" class="mb-4">
      <UiStatusMessage type="stats" :extra-info="extraInfo">
        <span class="text-xs">
          显示 <span class="text-text-primary font-semibold">{{ movieCount }}</span> 部电影
          <span v-if="hasActiveFilters" class="text-text-muted ml-1">(已筛选)</span>
        </span>
      </UiStatusMessage>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { UiButton, UiSelect, UiStatusMessage } from '../ui'
import { useTagManagement } from '../../composables/tags'

// Props
interface Props {
  showSort?: boolean
  showFilters?: boolean
  showStats?: boolean
  showGenreFilter?: boolean
  showUniverseFilter?: boolean
  showLanguageFilter?: boolean
  showCountryFilter?: boolean
  showAiFilter?: boolean
  movieCount?: number
  hasMore?: boolean
  extraInfo?: string
  initialFilters?: Record<string, string>
  initialSort?: string
  sortOptions?: Array<{
    key: string
    label: string
    icon: string
  }>
}

const props = withDefaults(defineProps<Props>(), {
  showSort: true,
  showFilters: true,
  showStats: true,
  showGenreFilter: true,
  showUniverseFilter: true,
  showLanguageFilter: true,
  showCountryFilter: true,
  showAiFilter: true,
  movieCount: 0,
  hasMore: false,
  extraInfo: '',
  initialFilters: () => ({
    genre: 'all',
    universe: 'all',
    language: 'all',
    country: 'all',
    ai: 'all'
  }),
  initialSort: 'views',
  sortOptions: () => [
    { key: 'relevance', label: '相关度', icon: '🎯' },
    { key: 'views', label: '播放量', icon: '👁️' },
    { key: 'updated_at', label: '最新更新', icon: '🕒' },
    { key: 'year', label: '上映年份', icon: '📅' },
    { key: 'rating', label: '评分最高', icon: '⭐' }
  ]
})

// Emits
const emit = defineEmits<{
  'update:filters': [filters: Record<string, string>]
  'update:sort': [sort: string]
  'clear-filters': []
}>()

// 标签管理
const { tags, fetchAllTags } = useTagManagement()

// 响应式数据
const currentSort = ref(props.initialSort)
const filters = ref({ ...props.initialFilters })

// 筛选选项
const genreOptions = computed(() => {
  const options = [{ value: 'all', label: '全部' }]
  if (tags.value.genre) {
    tags.value.genre.forEach(tag => {
      options.push({ value: tag.display_name, label: tag.display_name })
    })
  }
  return options
})

const universeOptions = computed(() => {
  const options = [{ value: 'all', label: '全部' }]
  if (tags.value.universe) {
    tags.value.universe.forEach(tag => {
      options.push({ value: tag.display_name, label: tag.display_name })
    })
  }
  return options
})

const languageOptions = computed(() => {
  const options = [{ value: 'all', label: '全部' }]
  if (tags.value.language) {
    tags.value.language.forEach(tag => {
      options.push({ value: tag.display_name, label: tag.display_name })
    })
  }
  return options
})

const countryOptions = computed(() => {
  const options = [{ value: 'all', label: '全部' }]
  if (tags.value.country) {
    tags.value.country.forEach(tag => {
      options.push({ value: tag.display_name, label: tag.display_name })
    })
  }
  return options
})

const aiOptions = [
  { value: 'all', label: '全部' },
  { value: 'ai', label: 'AI生成' },
  { value: 'human', label: '人工创作' }
]

// 计算属性
const hasActiveFilters = computed(() => {
  return filters.value.genre !== 'all' || 
         filters.value.universe !== 'all' || 
         filters.value.language !== 'all' || 
         filters.value.country !== 'all' || 
         filters.value.ai !== 'all'
})

// 方法
const selectSort = (sortKey: string) => {
  currentSort.value = sortKey
  emit('update:sort', sortKey)
}

const selectFilter = (filterType: string, value: string) => {
  filters.value[filterType as keyof typeof filters.value] = value
  emit('update:filters', { ...filters.value })
}

const clearFilters = () => {
  filters.value = {
    genre: 'all',
    universe: 'all',
    language: 'all',
    country: 'all',
    ai: 'all'
  }
  emit('clear-filters')
  emit('update:filters', { ...filters.value })
}

// 初始化标签数据
onMounted(async () => {
  try {
    await fetchAllTags()
  } catch (error) {
    console.error('初始化标签数据失败:', error)
  }
})
</script>
